package com.dmz.czykt.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author lee
 */
@Slf4j
public class HttpClient {
    /**
     * 5.发起POST请求
     *
     * @param url 请求url
     *            请求参数（json）
     * @return
     * @throws Exception JSONObject
     * @desc ：
     */
    public static JSONObject doPost2(String url, String json) throws Exception {
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属性
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(json, "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信息
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {

            // 3.3 发起请求，获取响应
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                log.info("POST请求结果：{}", resultStr);

                // 解析响应内容
                JSONObject result = JSONUtil.parseObj(resultStr);

                if (result.getInt("errcode") == null) {
                    return result;
                } else if (0 == result.getInt("errcode")) {
                    return result;
                } else {
                    log.info("request url={},return value=", url);
                    log.info(resultStr);
                    int errCode = result.getInt("errcode");
                    String errMsg = result.getStr("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            log.error("request url={}, exception, msg={}", url, e.getMessage());
            log.error(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }

        }
        return null;
    }
}
